package com.cdm.forum.controller;

import com.cdm.forum.common.Result;
import com.cdm.forum.common.ResultCode;
import com.cdm.forum.config.AppConfig;
import com.cdm.forum.model.Article;
import com.cdm.forum.model.ArticleReply;
import com.cdm.forum.model.User;
import com.cdm.forum.service.IArticleReplyService;
import com.cdm.forum.service.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/reply")
@Api(tags = "回复接口")
public class ArticleReplyController {

    @Resource
    private IArticleReplyService articleReplyService;

    @Resource
    private IArticleService articleService;

    @ApiOperation("新增回复帖子")
    @PostMapping("/createReply")
    private Result createReply(HttpServletRequest request,
            @ApiParam("帖子id") @RequestParam("articleId") @NonNull Long articleId,
            @ApiParam("帖子内容") @RequestParam("content") @NonNull String content) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //判断用户是否禁言
        if(user.getState() == 1) {
            return Result.failed(ResultCode.FAILED_USER_BANNED);
        }

        //获取帖子对象
        Article article = articleService.selectById(articleId);
        if(article == null || article.getDeleteState() == 1) {
            //返回帖子不存在
            return Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //是否封贴
        if(article.getState() == 1) {
            //表示帖子禁用
            return Result.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        //构建回复对象
        ArticleReply articleReply = new ArticleReply();
        articleReply.setContent(content);
        articleReply.setPostUserId(user.getId());
        articleReply.setArticleId(articleId);

        //调用service
        articleReplyService.createArticleReply(articleReply);

        return Result.success();

    }

    @ApiOperation("获取回复列表")
    @GetMapping("/getReplies")
    private Result<List<ArticleReply>> getArticleReplyByArticleId(
            @ApiParam("帖子id") @RequestParam("articleId") @NonNull Long articleId) {

        //根据帖子id查询帖子信息
        Article article = articleService.selectById(articleId);
        //校验帖子是否存在
        if(article == null || article.getDeleteState() == 1) {
            return Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //调用service层
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);

        return Result.success(articleReplies);
    }
}
